'''
悦宝保·学幼住院医疗保险
'''

import sys

sys.path.append('../..')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
import requests, json
from urllib.parse import urlencode
from common.helper import Helper


class Spider(object):
    def __init__(self):

        self.mysql = MysqlClient()

        self.name = "悦宝保·学幼住院医疗保险"

    # 生成产品数据
    def genProductInfo(self):

        plan = {

            "planA": {

                # 年龄段 3 - 18 周岁
                "year": [str(i) for i in range(3, 19)],
                # 性别 1 男 0 女
                "gender": ["1", "0"],
                # 方案
                "plan": ["planA"],
                # 有无社保
                "socialSec": ["Y", "N"],
                # 保额
                "money": ["20000"],
                # 加购白血病
                "ext_item": ["0" if i == 0 else str(i) + "0000" for i in range(0, 21)],
                # 介绍
                "introduce": {

                    "投保免赔额": "免赔额2万",

                    "住院医疗保险金": "50万"
                }

            },
            "planB": {

                # 年龄段 3 - 18 周岁
                "year": [str(i) for i in range(3, 19)],

                # 性别 1 男 0 女
                "gender": ["1", "0"],
                # 方案
                "plan": ["planB"],
                # 有无社保
                "socialSec": ["Y", "N"],
                # 保额
                "money": ["30000"],
                # 加购白血病
                "ext_item": ["0" if i == 0 else str(i) + "0000" for i in range(0, 21)],
                # 介绍
                "introduce": {

                    "投保免赔额": "免赔额3万",

                    "住院医疗保险金": "50万"
                }

            },
            "planC": {

                # 年龄段 3 - 18 周岁
                "year": [str(i) for i in range(3, 19)],
                # 性别 1 男 0 女
                "gender": ["1", "0"],
                # 方案
                "plan": ["planC"],
                # 有无社保
                "socialSec": ["Y", "N"],
                # 保额
                "money": ["40000"],
                # 加购白血病
                "ext_item": ["0" if i == 0 else str(i) + "0000" for i in range(0, 21)],
                # 介绍
                "introduce": {

                    "投保免赔额": "免赔额3万",

                    "住院医疗保险金": "50万"
                }

            },
            "planD": {

                # 年龄段 3 - 18 周岁
                "year": [str(i) for i in range(3, 19)],
                # 性别 1 男 0 女
                "gender": ["1", "0"],
                # 方案
                "plan": ["planD"],
                # 有无社保
                "socialSec":["Y","N"],
                # 保额
                "money": ["10000"],
                # 加购白血病
                "ext_item": ["0" if i == 0 else str(i) + "0000" for i in range(0, 21)],
                # 介绍
                "introduce": {

                    "投保免赔额": "免赔额1万",

                    "住院医疗保险金": "20万"
                }

            }
        }

        for k in plan:

            introduce = "'" + json.dumps(plan[k]["introduce"], ensure_ascii=False) + "'"

            expire = "1年"

            for v in product(plan[k]["year"], plan[k]["gender"], plan[k]["plan"], plan[k]["socialSec"],plan[k]["money"],
                             plan[k]["ext_item"]):

                print( domain[self.name]["insert_sql"].format(v[0], v[1], v[2], v[3], v[4],expire, v[5], introduce) )
                # 写入数据库
                self.mysql.cursor.execute(
                    domain[self.name]["insert_sql"].format(v[0], v[1], v[2], v[3], v[4],expire, v[5], introduce))

                self.mysql._conn.commit()

                print("%s产品信息写入数据库成功"%self.name )

    #执行爬虫
    def requestJson(self,dt=None):


        data = {

            "productCode": "XY_ZYYL",
            "deductible": dt["money"],
            "plan": dt["plan"],
            "socialSecurity": dt["socialSec"],
            "enterAge": dt["year"],
            "gender": dt["gender"],
            "optionalInsuredAmount": dt["ext_item"],
            "insured_gender": dt["gender"]
        }

        r = requests.post( url = domain[self.name]["url"],headers=domain[self.name]["header"],data=urlencode(data).replace("+",""))

        if r.status_code == 200 and "price" in r.json():

            print( r.json() )
            price = Helper.decimalParse( r.json()["price"])

            data = {

                "name":self.name,
                "price":price,
                "id":dt["id"]
            }

            self.mysql.updatePrice( data )

        else:

            data = {

                "name":self.name,
                "state":3,
                "id":dt["id"]
            }

            self.mysql.updateTask( data )

    def main(self):

        while True:

            # 随机领取一条数据
            dt = self.mysql.randTask(self.name)

            if not dt:
                print("产品价格抓取完成~~~")

                return

                # 任务执行状态
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 1
            }
            self.mysql.updateTask(data)

            self.requestJson(dt)

